package com.wkk.utils;

import com.wkk.pojo.Content;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
   *
   * @author : WangKeKe
   * @date : 2020/7/11 22:49
   * Description :
   *
 */


@Component
public class HtmlParseUtil {

    /*public static void main(String[] args) throws IOException {
        new HtmlParseUtil().paresJD("Java").forEach(System.out::println);
        // System.out::println
        // (content)-> System.out.println(content)
    }*/
    public List<Content> paresJD(String keywords)throws IOException{
        List<Content> contents = new ArrayList<>();
        String url = "https://search.jd.com/Search?keyword="+keywords;
        Document document = Jsoup.parse(new URL(url), 30000);
        Element element = document.getElementById("J_goodsList");
        Elements elementsByTag = element.getElementsByTag("li");
        for (Element el:elementsByTag
        ) {
            String img = el.getElementsByTag("img").eq(0).attr("src");
            String price = el.getElementsByTag("em").eq(0).text()+el.getElementsByTag("i").eq(0).text();
            String title = el.getElementsByTag("em").eq(1).text();
            contents.add(new Content(title,img,price));
        }
        return contents;
    }
}

